package com.hdd.hll.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hdd.hll.common.config.Global;
import com.hdd.hll.common.response.ResponseIo;
import com.hdd.hll.common.response.ResponseUtils;
import com.hdd.hll.common.utils.SignUtils;
import com.hdd.hll.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author H 登录token验证拦截器
 */
@Slf4j
@Component("authSecurityInterceptor")
public class LoginInterceptor extends HandlerInterceptorAdapter {

	public static String isSign = Global.getConfig("hdd.has.sign");

	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
		try {
			RequestWrapper requestWrapper = new RequestWrapper(httpServletRequest);

			SortedMap<Object,Object> parameters = new TreeMap<>();
			// 签名逻辑
			 if(!StringUtils.isNullOrEmpty(isSign)&& isSign.toUpperCase().equals("YES")){
				 String body = requestWrapper.getBody();
				 if(!StringUtils.isNullOrEmpty(body)){
					 JSONObject jsonObject = JSON.parseObject(body);
					 parameters = SignUtils.toSortedMap(jsonObject);
				 }

				 StringBuffer url =requestWrapper.getRequestURL();
				 parameters.put("url",url);

				 System.out.println(parameters);

				 String sign = SignUtils.createSign(parameters);

				 System.out.println(sign);

				 String authorization = requestWrapper.getHeader("Authorization");
				 if(StringUtils.isNullOrEmpty(authorization)){
					 ResponseIo.responseOut(httpServletResponse, ResponseUtils.initsByCode("common.sign.error"));
				 }

				 if(!sign.equals(authorization) ){
					 ResponseIo.responseOut(httpServletResponse, ResponseUtils.initsByCode("common.sign.error"));
					 return false;
				 }
			}

			return true;
		}catch (Exception e){
			log.error("权限判断出错",e);
		}
		return false;
	}




	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
	}

}
